<template>
<div class="flexX" v-loading="loading">
  <div class="purchaseContainer">
    <el-page-header @back="goBack" style="margin-left: 50px;"/>
    <div class="content" >

      <el-form :model="form" label-width="320px">
        <el-form-item label="购买数量">
          <el-input v-model="form.count" />
        </el-form-item>
        <el-form-item label="收货人姓名">
          <el-input v-model="form.consignee" />
        </el-form-item>
        <el-form-item label="收货地址">
          <el-input v-model="form.addr" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-button
            @click="sumbit"
            type="primary"
            style="width: 90%;margin-left: 200px">提交订单</el-button>
      </el-form>

      <el-dialog v-model="dialogFormVisible" title="Shipping address">
        <el-form :model="form">
          <el-form-item label="支付密码" :label-width="formLabelWidth">
            <el-input v-model="form.payPassword" autocomplete="off" type="password" />
          </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelHandle">取消</el-button>
        <el-button type="primary" @click="sumbitHandle">
          确认
        </el-button>
      </span>
        </template>
      </el-dialog>



    </div>
  </div>
</div>
</template>

<script setup>

import router from "@/router";
import {reactive, ref} from "vue";
import axios from "axios";
import store from "@/store";
import {ElMessage} from "element-plus";

const dialogFormVisible = ref(false)
const loading = ref(false)
const formLabelWidth = '140px'
const form = reactive({
  addr: '',
  count: '',
  consignee: '',
  phone: '',
  payPassword: '',
})

const goBack = () => {
  router.back()
}
const cancelHandle = () => {
  dialogFormVisible.value = false
  loading.value = false
}
const sumbitHandle = () => {
  if (form.payPassword !== store.state.user.payPassword) {
    ElMessage({
      message: '支付密码错误，请重试',
      type: 'warning'
    })
  } else {
    axios.get(`/api/order/${store.state.user.id}/${store.state.book.id}/${form.consignee}/${form.addr}/${form.phone}/${form.count}`)
        .finally(() => {
          ElMessage({
            message: '添加成功',
            type: 'success'
          })
          dialogFormVisible.value = false
          loading.value = false

          ElMessage({
            message: '正在进入订单页面',
            type: 'success'
          })

          setTimeout(() => {
            router.push('/order')
          } , 2000)

        })
  }
}
const sumbit = ()=> {
  loading.value = true;
  dialogFormVisible.value = true

}
</script>

<style scoped>
.purchaseContainer{
  width: var(--content);
  min-height: 400px;
  background-color:white;
}
.content{
  width: 80%;
}
</style>